package com.eims.sls_app.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.CircleBean;
import com.eims.sls_app.dataaccess.CircleBean.CommentBean;
import com.eims.sls_app.dataaccess.CircleBean.SchemeinfoBean;
import com.eims.sls_app.dataaccess.CircleBean.TopicBean;
import com.eims.sls_app.dataaccess.CircleBean.SchemeinfoBean.InformationIdBean;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.CircleAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.App;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class SearchForPersonActivity extends MyBaseActivity implements OnClickListener {

	private String TAG = "SearchForPersonActivity";
	private Activity activity;
	private PullToRefreshListView circle_item_listView;
	private String opt, auth, info, time, imei, crc; // 格式化后的参数
	private String userId;
	private MyHandler mHandler;
	private MyAsynTask mMyAsynTask;
	private MySingleton mySingleton;
	private CircleBean circleBean;
	private InformationIdBean informationIdBean;
	private CircleAdapter circleAdapter;
	private boolean isToFirst = true;

	private ImageView ivBack;
	private EditText etInput;
	private TextView tvSearch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);

		setContentView(R.layout.search_for_person);
		App.activityS.add(this);
		App.activityS1.add(this);
		SharedPreferences myAhare =getSharedPreferences("pinglun", Activity.MODE_PRIVATE);
		// 实例化SharedPreferences.Editor对象（第二步）
		SharedPreferences.Editor editor = myAhare.edit();
		// 用putString的方法保存数据
		editor.putInt("isfr", 0);
		mHandler = new MyHandler();
		Log.e("11", "11");
		init();

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
	Log.e("time", "onResume");
		
		
		
		SharedPreferences sharedPreferences= getSharedPreferences("pinglun", 
				Activity.MODE_PRIVATE); 
				// 使用getString方法获得value，注意第2个参数是value的默认值 
				int isfo =sharedPreferences.getInt("isfr", 0); 
			
				if (isfo==1) {
					int  myuid =sharedPreferences.getInt("uid", 0); 
					int myposition =sharedPreferences.getInt("position", 0); 
					int myid =sharedPreferences.getInt("id", 0); 
					int mycid =sharedPreferences.getInt("cid", 0); 
					String mydetail =sharedPreferences.getString("detail", ""); 
					String mytime =sharedPreferences.getString("time", ""); 
					String myname =sharedPreferences.getString("name", ""); 
					String mydatetime =sharedPreferences.getString("datetime", ""); 
					String myrid =sharedPreferences.getString("rid", "");
					String myrname =sharedPreferences.getString("rname", "");
					String myruid =sharedPreferences.getString("ruid", "");
					CommentBean commentBean = new CommentBean();
					commentBean.id =myid;
					commentBean.cid = mycid;
					commentBean.uid = myuid;
					commentBean.detail = mydetail;
					commentBean.time = mytime;
					commentBean.name = myname;
					commentBean.datetime = mydatetime;
					commentBean.rid = myrid;
					commentBean.rname = myrname;
					commentBean.ruid = myruid;
					circleAdapter.setComm(myposition, commentBean);
					
					Log.e(TAG, commentBean.toString());
					ProgressDialogBar.stopProgress();
				}
				
				SharedPreferences myAhare =getSharedPreferences("pinglun", Activity.MODE_PRIVATE);
				// 实例化SharedPreferences.Editor对象（第二步）
				SharedPreferences.Editor editor = myAhare.edit();
				// 用putString的方法保存数据
				editor.putInt("isfr", 0);
				
				editor.commit();
		super.onResume();
	}

	private void init() {
		circle_item_listView = (PullToRefreshListView) findViewById(R.id.circle_item_listView);
		ivBack = (ImageView) findViewById(R.id.btn_back);
		etInput = (EditText) findViewById(R.id.et_input);
		tvSearch = (TextView) findViewById(R.id.btn_search);
		ivBack.setOnClickListener(this);
		tvSearch.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_search:
			if (etInput.getText().toString() != null && !etInput.getText().toString().equals("")) {
				info = etInput.getText().toString();
				
				ProgressDialogBar.startProgress(this, "加载", false);
				MyAsynTask myAsynTask = new MyAsynTask();
				myAsynTask.execute();
			} else {
				Toast.makeText(this, "搜索内容不能为空，请重新填写！", Toast.LENGTH_SHORT).show();
			}

			break;
		default:
			break;
		}
	}

	class MyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "96";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(SearchForPersonActivity.this);
			// info = RspBodyBaseBean.change_TheSun(schemeId+"", context_Sun);
			// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
			String key = App.key;
			if (App.user == null) {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info, "-1");
				auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");
			} else {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
				auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			}

			String[] values = { opt, auth, info };
			Log.i(TAG, "晒单" + RequestParams.convertParams(SearchForPersonActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			System.out.println("晒单：" + result);
			Log.i(TAG, "晒单" + result);
			if ("-500".equals(result)) {
				return "-500";
			}

			circleBean = new CircleBean();
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONArray topic = jsonObject.getJSONArray("topic");
				List<TopicBean> topicBeans = new ArrayList<CircleBean.TopicBean>();
				if (topic.equals("[]")) {
					error = "1";
				}
				for (int i = 0; i < topic.length(); i++) {

					JSONObject obj = topic.getJSONObject(i);
					TopicBean topicBean = new TopicBean();
					topicBean.id = obj.optInt("id");
					topicBean.userid = obj.optInt("userid");
					topicBean.detail = obj.optString("detail");
					topicBean.schemeid = obj.optInt("schemeid");
					topicBean.up = obj.optString("up");
					topicBean.datetime = obj.optString("datetime");
					topicBean.enable = obj.optBoolean("enable");
					topicBean.yjjj = obj.optString("yjjj");
					topicBean.stoptime = obj.getString("stoptime");
					topicBean.cancopy = obj.getBoolean("cancopy");
					topicBean.name = obj.optString("name");
					topicBean.HeadUrl = obj.optString("HeadUrl");
					topicBean.Wins = obj.optString("Wins");
					topicBean.iswin = obj.optString("iswin");
					topicBean.interest = obj.optString("interest");
					topicBean.PlayTypeID = obj.optString("PlayTypeID");
					topicBean.hb = obj.optString("hb");
					topicBeans.add(topicBean);
				}
				JSONArray comment = jsonObject.getJSONArray("comment");
				List<List<CommentBean>> commentBeans = new ArrayList<List<CommentBean>>();
				for (int i = 0; i < comment.length(); i++) {
					JSONArray jsonArray = comment.getJSONArray(i);
					if(jsonArray == null || jsonArray.length() == 0){
						continue;
					}
					List<CommentBean> commentBeanlists = new ArrayList<CircleBean.CommentBean>();
					for (int j = 0; j < jsonArray.length(); j++) {
						JSONObject object2 = jsonArray.getJSONObject(j);
						CommentBean commentBean = new CommentBean();
						commentBean.id = object2.optInt("id");
						commentBean.cid = object2.optInt("cid");
						commentBean.uid = object2.optInt("uid");
						commentBean.detail = object2.optString("detail");
						commentBean.time = object2.optString("time");
						commentBean.name = object2.optString("name");
						commentBean.datetime = object2.optString("datetime");
						commentBean.rname = object2.optString("rname");
						commentBean.rid = object2.optString("rid");
						commentBean.ruid = object2.optString("ruid");
						commentBeanlists.add(commentBean);
					}
					commentBeans.add(commentBeanlists);
				}

				JSONArray schemeinfo = jsonObject.getJSONArray("schemeinfo");
				List<SchemeinfoBean> schemeinfoBeans = new ArrayList<CircleBean.SchemeinfoBean>();

				for (int i = 0; i < schemeinfo.length(); i++) {
					JSONObject object = schemeinfo.getJSONObject(i);
					SchemeinfoBean schemeinfoBean = new SchemeinfoBean();
					schemeinfoBean.buymoney = object.optString("buymoney");
					schemeinfoBean.buyTime = object.optString("buyTime");
					schemeinfoBean.preBetType = object.optString("preBetType");
					schemeinfoBean.isHide = object.optInt("isHide");
					schemeinfoBean.stopsellingtime = object.optString("stopsellingtime");
					schemeinfoBean.secretMsg = object.optString("secretMsg");
					schemeinfoBean.passTypeInfo = object.optString("passTypeInfo");
					// JSONArray optimization = object.getJSONArray("optimization");
					JSONArray InformationId = object.getJSONArray("informationId");
					List<InformationIdBean> informationIdBeans = new ArrayList<CircleBean.SchemeinfoBean.InformationIdBean>();
					for (int j = 0; j < InformationId.length(); j++) {
						JSONObject jsonObject2 = InformationId.getJSONObject(j);
						informationIdBean = new InformationIdBean();
						informationIdBean.ID = jsonObject2.optString("ID");
						informationIdBean.SchemeID = jsonObject2.optString("SchemeID");
						informationIdBean.PlayType = jsonObject2.optString("PlayType");
						informationIdBean.MatchNumber = jsonObject2.optString("MatchNumber");
						informationIdBean.Game = jsonObject2.optString("Game");
						informationIdBean.MaiTeam = jsonObject2.optString("MaiTeam");
						informationIdBean.GuestTeam = jsonObject2.optString("GuestTeam");
						informationIdBean.StopSelling = jsonObject2.optString("StopSelling");
						informationIdBean.LetBile = jsonObject2.optString("LetBile");
						informationIdBean.Score = jsonObject2.optString("Score");
						informationIdBean.Results = jsonObject2.optString("Results");
						informationIdBean.PassType = jsonObject2.optString("PassType");
						informationIdBean.issue = jsonObject2.optString("issue");
						informationIdBean.Status = jsonObject2.optString("Status");
						informationIdBean.EndTime = jsonObject2.optString("EndTime");
						informationIdBean.investContent = jsonObject2.optString("investContent");
						informationIdBean.Content = jsonObject2.optString("Content");
						informationIdBean.MainLoseball = jsonObject2.optString("MainLoseball");
						informationIdBean.LetScore = jsonObject2.optString("LetScore");
						informationIdBean.BigSmallScore = jsonObject2.optString("BigSmallScore");
						informationIdBean.strresult = jsonObject2.optString("strresult");
						informationIdBeans.add(informationIdBean);

					}
					schemeinfoBean.informationId = informationIdBeans;
					schemeinfoBeans.add(schemeinfoBean);
				}
				circleBean.comment = commentBeans;
				circleBean.topic = topicBeans;
				circleBean.schemeinfo = schemeinfoBeans;
			} catch (JSONException e) {

				e.printStackTrace();
			}
			error = "0";
			return error;
		}

		@Override
		protected void onPostExecute(String result) {

			mHandler.sendEmptyMessage(Integer.parseInt(result));

			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			ProgressDialogBar.stopProgress();
			switch (msg.what) {
			case 0:

				circleAdapter = new CircleAdapter(SearchForPersonActivity.this, circleBean.topic, circleBean.schemeinfo,
						circleBean.comment);
				circle_item_listView.setAdapter(circleAdapter);
				try {
					if (circleBean.topic.size()==0) {
						Toast.makeText(SearchForPersonActivity.this, "没有搜索信息", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(SearchForPersonActivity.this, "没有搜索信息", Toast.LENGTH_SHORT).show();
				}
				
				// MyToast.getToast(context, "晒单成功").show();
				break;
			case 1:

				// MyToast.getToast(context, "重复晒单").show();
				break;
			case -1:

				break;
			case -500:

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	}

}
